<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import { getDictionaryDataByTypeKey, addDictionaryData, updateDictionaryData, deleteDictionaryData, getDictionaryDataChildrenCount } from '@/api/dictionary'
import DictionaryDataDialog from './component/DictionaryDataDialog.vue'

const route = useRoute()
const typeKey = ref('')

// 数据列表
const tableData = ref([])

// 分页参数
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 筛选参数
const searchForm = reactive({
  value: '',
  typeKey: ''
})

// 弹窗控制
const dialogVisible = ref(false)
const dialogMode = ref('add')
const currentRow = ref({})

// 打开新增弹窗
const handleAdd = () => {
  dialogMode.value = 'add'
  currentRow.value = {}
  dialogVisible.value = true
}
// 打开编辑弹窗
const handleEdit = (row) => {
  dialogMode.value = 'edit'
  currentRow.value = { ...row }
  dialogVisible.value = true
}
// 弹窗提交
const handleDialogSubmit = async (formData) => {
  try {
    if (dialogMode.value === 'add') {
      await addDictionaryData(formData)
      ElMessage.success('新增成功')
    } else {
      await updateDictionaryData({ ...formData, id: currentRow.value.id })
      ElMessage.success('编辑成功')
    }
    getList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 获取数据列表
const getList = async () => {
  try {
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      value: searchForm.value,
      typeKey: searchForm.typeKey
    }
    const res = await getDictionaryDataByTypeKey(params)
    tableData.value = res.list || []
    pagination.total = res.totals || 0
  } catch (error) {
    console.error('获取字典数据失败:', error)
    ElMessage.error('获取字典数据失败')
  } finally {
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = ''
  pagination.current = 1
  getList()
}

// 分页变化
const handlePageChange = (page) => {
  pagination.current = page
  getList()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.current = 1
  getList()
}



// 删除字典数据
const handleDelete = async (row) => {
  try {
    let confirmMessage = `确定要删除字典数据 "${row.value}" 吗？删除后不可恢复！`
    
    // 通过接口获取子级数量
    try {
      const childrenCount = await getDictionaryDataChildrenCount(row.dataKey)
      
      if (childrenCount > 0) {
        confirmMessage = `字典数据 "${row.value}" 存在 ${childrenCount} 个子级数据。\n\n删除后将连同所有子级数据一起删除，且不可恢复！\n\n确定要删除吗？`
      }
    } catch (error) {
      console.warn('获取子级数量失败，继续执行删除:', error)
    }
    
    await ElMessageBox.confirm(
      confirmMessage,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    await deleteDictionaryData(row.dataKey)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  typeKey.value = route.params.typeKey
  searchForm.typeKey = typeKey.value
  getList()
})

// 监听路由变化（如果详情页支持切换typeKey）
watch(() => route.params.typeKey, (newVal) => {
  typeKey.value = newVal
  searchForm.typeKey = newVal
  handleReset()
})
</script>

<template>
  <div class="dictionary-detail-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="字典类型">
          <el-input v-model="searchForm.typeKey" readonly style="width: 200px" />
        </el-form-item>
        <el-form-item label="字典描述">
          <el-input
            v-model="searchForm.value"
            placeholder="请输入字典描述"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div style="display: flex; justify-content: flex-end;">
          <el-button type="primary" @click="handleAdd">新增字典数据</el-button>
        </div>
      </template>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="120" />
        <el-table-column label="图标" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.icon"
              :src="row.icon"
              style="width: 40px; height: 40px"
              fit="cover"
              :preview-src-list="[row.icon]"
            />
            <span v-else class="no-icon">无图标</span>
          </template>
        </el-table-column>
        <el-table-column prop="dataKey" label="字典键" />
        <el-table-column prop="parentDataKey" label="父级字典键" width="120">
          <template #default="{ row }">
            <span v-if="row.parentDataKey">{{ row.parentDataKey }}</span>
            <span v-else class="no-parent">--</span>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="字典描述" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <DictionaryDataDialog
      :visible="dialogVisible"
      :mode="dialogMode"
      :data="currentRow"
      :typeKey="typeKey"
      :allData="tableData"
      @update:visible="dialogVisible = $event"
      @submit="handleDialogSubmit"
    />
  </div>
</template>

<style scoped lang="scss">
.dictionary-detail-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
  
  .no-icon {
    color: #999;
    font-size: 12px;
  }
  
  .no-parent {
    color: #999;
    font-size: 12px;
  }
}
</style>